import { Button, Calendar, DatePicker, Divider, Dropdown, Input, InputNumber, List, message, Popconfirm, Space, Tag } from "antd";
import dayjs, { Dayjs } from 'dayjs';
import type { DatePickerProps, MenuProps } from 'antd';
import { useEffect, useState } from "react";
import { useMediaQuery } from 'react-responsive'
import { DeleteTask, editStatus, editTask, listTask, saveTask } from "@/clientApi/task";
import { DatePicker as MobileDatePicker } from 'antd-mobile';
import { globalMessage } from "@/utils/message";

// 任务项接口定义
interface TaskItem {
  taskId: string;
  title: string;
  description: string;
  currentOrder: number;
  startTime: string;
  endTime: string;
  userId: string;
  overStatus: boolean;
  [key: string]: any; // 允许其他额外属性
}

// 组件属性接口
interface TaskListViewProps {
  list: TaskItem[];
  startTime: string;
  handleCancle: () => void;
}

// 查询参数接口
interface QueryParams {
  taskId?: string;
  title: string;
  description: string;
  currentOrder: number;
  startTime: string | null;
  endTime: string | null;
  userId: string | null;
}

const TaskListView: React.FC<TaskListViewProps> = (props) => {
  const isMobile = useMediaQuery({ maxWidth: 768 })
  const [isCreateMobileDateOpen, setIsCreateMobileDateOpen] = useState<boolean>(false)
  const [isEndMobileDateOpen, setIsEndMobileDateOpen] = useState<boolean>(false)

  const [taskList, setTaskList] = useState<TaskItem[]>([])
  const [isOpen, setIsOpen] = useState<boolean>(false)
  
  // 初始查询参数
  const initialQuery: QueryParams = {
    title: '',
    description: '',
    startTime: null,
    currentOrder: 0,
    endTime: null,
    userId: "2",
  }
  
  const [queryParams, setQueryParams] = useState<QueryParams>(initialQuery)

  useEffect(() => {
    setTaskList([...props.list])
    setQueryParams(prev => ({
      ...prev,
      startTime: props.startTime,
      endTime: props.startTime
    }))
  }, [props.list, props.startTime])

  // 生成操作菜单
  const getMenuItems = (item: TaskItem): MenuProps['items'] => [
    {
      key: '0',
      label: (
        <Popconfirm
          title="删除"
          description={`是否删除taskId为${item.taskId}的数据`}
          okText="是"
          placement="leftTop"
          onConfirm={() => handleDeleteClick(item)}
          cancelText="否"
        >
          <Button type="link" size="small">删除</Button>
        </Popconfirm>
      ),
    },
    {
      key: '1',
      label: (
        <Popconfirm
          title="是否修改状态"
          okText="是"
          placement="leftTop"
          onConfirm={() => handleStatusClick(item)}
          cancelText="否"
        >
          <Button type="link" size="small">状态</Button>
        </Popconfirm>
      ),
    },
    {
      key: '2',
      label: <Button type="link" size="small" onClick={() => handleClick(item)}>修改</Button>,
    },
  ];

  // 处理修改任务
  const handleClick = (item: TaskItem) => {
    setQueryParams({
      ...item
    })
    setIsOpen(true)
  }

  // 处理新增任务
  const handleAdd = () => {
    setQueryParams({ 
      ...initialQuery, 
      startTime: props.startTime, 
      endTime: props.startTime 
    })
    setIsOpen(true)
  }

  // 处理状态修改
  const handleStatusClick = (item: TaskItem) => {
    const completed = !item.overStatus;
    editStatus({ 
      taskId: item.taskId, 
      date: props.startTime, 
      completed 
    }).then((res: any) => {
      if (res.code === 200) {
        globalMessage().success(`修改成功`)
        props.handleCancle()
      }
    })
  }

  // 取消操作
  const handleCancle = () => {
    setIsOpen(false)
    props.handleCancle()
  }

  // 处理删除任务
  const handleDeleteClick = (item: TaskItem) => {
    const taskIds = [item.taskId]
    DeleteTask(taskIds).then((res: any) => {
      if (res.code === 200) {
        globalMessage().success(`已删除${res.data}`)
        props.handleCancle()
      }
    })
  }

  // 保存任务
  const handSave = () => {
    if (!queryParams.startTime || !queryParams.endTime) {
      globalMessage().warning("请选择开始和结束时间")
      return;
    }

    const dayjsTime1 = dayjs(queryParams.startTime, 'YYYY-MM-DD HH:mm:ss');
    const dayjsTime2 = dayjs(queryParams.endTime, 'YYYY-MM-DD HH:mm:ss');
    
    if (!dayjsTime2.isAfter(dayjsTime1)) {
      globalMessage().warning("结束时间要晚于开始时间")
      return;
    }
    
    if (!queryParams.title || !queryParams.description) {
      globalMessage().warning("请填写标题和内容")
      return;
    }

    if (!queryParams.taskId) {
      saveTask(queryParams).then((res: any) => {
        if (res.code === 200) {
          globalMessage().success("保存成功")
          handleCancle()
        }
      })
    } else {
      editTask(queryParams).then((res: any) => {
        if (res.code === 200) {
          globalMessage().success("修改成功")
          handleCancle()
        }
      })
    }
  }

  return (
    <div className="w-full">
      {!isOpen ? (
        <div>
          <div className="pl-1 flex justify-between">
            <Button onClick={handleAdd} type="link" size="small">
              新增
            </Button>
            <Button onClick={props.handleCancle} type="link" size="small">
              刷新
            </Button>
          </div>

          <List
            itemLayout="horizontal"
            dataSource={taskList}
            renderItem={(item) => (
              <div className="p-2">
                <div className="w-full p-1 border border-inherit rounded-xl">
                  <div className="flex justify-between items-center pb-2">
                    <div className="w-5/6 flex">
                      <div>{item.title}</div>
                      <div className="pl-2"></div>
                    </div>
                    <div className="w-1/6 text-right pr-3">
                      <Dropdown menu={{ items: getMenuItems(item) }} trigger={['click']}>
                        <a className="text-blue-500" onClick={(e) => e.preventDefault()}>
                          操作
                        </a>
                      </Dropdown>
                    </div>
                  </div>
                  <div className="flex justify-between items-center">
                    <div className="w-5/6">{item.description}</div>
                    <div className="w-1/6 text-right">
                      <Tag color={item.overStatus ? "blue" : "gold"}>
                        {item.overStatus ? "已完成" : '未完成'}
                      </Tag>
                    </div>
                  </div>
                </div>
              </div>
            )}
          />
        </div>
      ) : (
        <div>
          <div className="flex justify-between">
            <Button type="link" onClick={handleCancle}>返回</Button>
            <Button type="link" onClick={handSave}>保存</Button>
          </div>
          <Divider plain></Divider>
          <div className="m-2">
            <div className="w-2/4 pb-2">
              {/* 开始时间选择 */}
              {isMobile ? (
                <div>
                  <Button onClick={() => setIsCreateMobileDateOpen(true)}>
                    开始： {queryParams.startTime || ''}
                  </Button>
                  <MobileDatePicker 
                    visible={isCreateMobileDateOpen}
                    onClose={() => setIsCreateMobileDateOpen(false)}
                    precision='minute'
                    onConfirm={(value: any) => {
                      setIsCreateMobileDateOpen(false)
                      setQueryParams(prev => ({ 
                        ...prev, 
                        startTime: value.format('YYYY-MM-DD HH:mm:ss') 
                      }))
                    }} 
                  />
                </div>
              ) : (
                <DatePicker
                  prefix="开始"
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  defaultValue={queryParams.startTime ? dayjs(queryParams.startTime) : undefined}
                  onOk={(value) => {
                    if (value) {
                      setQueryParams(prev => ({ 
                        ...prev, 
                        startTime: value.format('YYYY-MM-DD HH:mm:ss') 
                      }))
                    }
                  }}
                />
              )}
              
              {/* 结束时间选择 */}
              {isMobile ? (
                <div>
                  <Button onClick={() => setIsEndMobileDateOpen(true)}>
                    结束： {queryParams.endTime || ''}
                  </Button>
                  <MobileDatePicker 
                    visible={isEndMobileDateOpen}
                    onClose={() => setIsEndMobileDateOpen(false)}
                    precision='minute'
                    onConfirm={(value:any) => {
                      setIsEndMobileDateOpen(false)
                      setQueryParams(prev => ({ 
                        ...prev, 
                        endTime: value.format('YYYY-MM-DD HH:mm:ss') 
                      }))
                    }} 
                  />
                </div>
              ) : (
                <DatePicker
                  prefix="结束"
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm:ss"
                  defaultValue={queryParams.endTime ? dayjs(queryParams.endTime) : undefined}
                  onOk={(value) => {
                    if (value) {
                      setQueryParams(prev => ({ 
                        ...prev, 
                        endTime: value.format('YYYY-MM-DD HH:mm:ss') 
                      }))
                    }
                  }}
                />
              )}
            </div>
            
            <div className="w-2/4 pl-1 pb-2">
              <Input 
                placeholder='请输入标题' 
                onChange={(e) => setQueryParams(prev => ({ ...prev, title: e.target.value }))} 
                value={queryParams.title}
              />
            </div>
            
            <div className="w-2/4 pl-1 pb-2">
              <InputNumber 
                placeholder='请输入序号' 
                onChange={(e) => setQueryParams(prev => ({ ...prev, currentOrder: e || 0 }))} 
                value={queryParams.currentOrder}
              />
            </div>
            
            <div className="w-11/12 pl-1 pr-1">
              <Input.TextArea 
                placeholder='请输入描述信息' 
                onChange={(e) => setQueryParams(prev => ({ ...prev, description: e.target.value }))} 
                value={queryParams.description}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default TaskListView;